package com.hippo.core.ui.compose.spt

import android.os.Build
import android.text.Html
import android.text.Spanned
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.hippo.core.R
import com.hippo.core.model.FaqDetail
import com.hippo.core.ui.components.CommonBody
import com.hippo.core.ui.theme.HippoTheme
import com.hippo.core.vm.SptVm

@Composable
fun FaqDetailScreen(faqId: Int, onBack: () -> Unit, vm: SptVm = viewModel()) {

    val uiState = vm.uiState

    LaunchedEffect(Unit) {
        vm.getSptDetail(faqId)
    }

    FaqDetailContent(
        uiState.faqDetail,
        onBack = onBack
    )

}


@Composable
fun FaqDetailContent(detail: FaqDetail?, onBack: () -> Unit) {

    CommonBody(
        title = stringResource(R.string.spt_5),
        onBack = onBack,
        modifier = Modifier.padding(16.dp)
    ) {

        detail?.let {


            Text(
                text = detail.faqTitle.orEmpty(),
                style = TextStyle(
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 10.dp)
            )

            Text(
                text = htmlToAnnotatedString(it.faqContent.orEmpty()),
                style = TextStyle(
                    fontSize = 16.sp,
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState())
            )
        }

    }

}


@Composable
fun htmlToAnnotatedString(html: String): AnnotatedString {
    val spanned: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
    } else {
        Html.fromHtml(html)
    }

    val text = buildAnnotatedString {
        append(spanned)
    }
    return text
}

@Preview(showBackground = true)
@Composable
private fun FaqDetailContentPreview() {
    HippoTheme {
        FaqDetailContent(
            detail = FaqDetail(

            ),
            onBack = {}
        )
    }
}
